package com.ruoyi.app.login;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtFilter {
    private static final long EX_TIME = 1000 * 60 * 60 ;
    private static final String SECRET = "MDk4ZjZi789y438h9jikog5tfr4dew7gg5ft4689iy6t5f4rd3y679uiy6t5f4ry9uyg5tf4rh9jikog5tf4rd38h9ujiyg5fr4d38h9juig5tf4rd3h9juiyg5ft4r9jigt5f4rY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY";

    public static String createToken(Map<String,Object> map){
        long exp = System.currentTimeMillis() ;

        return Jwts.builder()
                .setClaims(map)
                .setIssuedAt(new Date(exp))
                .setExpiration(new Date(exp + EX_TIME))
                .signWith(SignatureAlgorithm.HS512,SECRET)
                .compact();
    }


    public static Claims parseToken(String token){
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }

    public static Map<String,Object> getClaims(String token){
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }

    public static JwsHeader getHeader(String token){
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getHeader();
    }

    public static Integer getId(String token){
        Claims claims = parseToken(token);
        if(claims==null){
            return 0;
        }
        if (new Date().before(claims.getExpiration())){
            return 1;
        }
        return 0;
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", "1");
        map.put("userName", "狗剩");
        map.put("authorities", Arrays.asList("student:add","user:list"));

        String token = createToken(map);
        System.err.println(token);

        Map<String, Object> claimsMap = getClaims(token);
        System.out.println(claimsMap);


    }
}
